/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package service.reportCenter.kegReport;

import com.openbrew.openbrewrf.Customer;
import com.openbrew.openbrewrf.PackageType;
import com.openbrew.openbrewrf.ScanTblKeg;
import com.openbrew.openbrewrf.views.POSBeerView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 *
 * @author chapmand
 */
@Stateless
@Path("com.openbrew.openbrewrf.kegreport")
public class KegReportREST {

    @PersistenceContext(unitName = "com.openBrew_openBrewRF_war_1.0PU")
    private EntityManager em;

    public KegReportREST() {
    }

    @GET
    @Path("{custID}/{ptID}/{beerID}")
    @Produces(MediaType.APPLICATION_XML)
    public List<KegReport> find(@PathParam("custID") Integer custID, @PathParam("ptID") Integer pkgID, @PathParam("beerID") Integer beerID) {
        return runReport(custID, pkgID, beerID);
    }
    
    @GET
    @Path("getCSV/{custID}/{ptID}/{beerID}")
    @Produces({"text/plain"})
    public Response createCSV(@PathParam("custID") Integer custID, @PathParam("ptID") Integer pkgID, @PathParam("beerID") Integer beerID) {
        List<KegReport> kegRep = runReport(custID, pkgID, beerID);

        String csvStr = "Keg Number,Customer,Keg Type,Beer Name,Date Sold,Days Checked Out";
        csvStr += "\n";

        for(KegReport k : kegRep){
            csvStr += Integer.toString(k.getKegID()) + ",";
            csvStr += k.getCustomerName() + ",";
            csvStr += k.getPackageName() + ",";
            csvStr += k.getBeerName() + ",";
            csvStr += k.getKegSoldDate().toString() + ",";
            csvStr += Integer.toString(k.getDays());
            csvStr += "\n";
        }
        return Response.ok(csvStr).header("Content-Disposition", "attachment; filename=ptReport.csv").build();
    }

    private List<KegReport> runReport(final int custID, final int pkgID, final int beerID) {
        final java.util.Date today = new java.util.Date();
        List<KegReport> kArray = new ArrayList<KegReport>();
        List<ScanTblKeg> kegs = getAllKegs(em);

        for (final ScanTblKeg keg : kegs) {
            String custName = "None";
            if (keg.getKegCust() != null) {
                Customer cust = keg.getKegCust();
                custName = cust.getCName();
            }
            String pkgType = "None";
            if (keg.getKegPackageID() != null) {
                PackageType pt = keg.getKegPackageID();
                pkgType = pt.getPackageTypeDesc();
            }
            String beerType = "None";
            if (keg.getKegBeer() != null) {
                POSBeerView beer = keg.getKegBeer();
                beerType = beer.getbName();
            }

            //Calculate days out.\
            int days = 0;
            if (keg.getDateSold() != null) {
                GregorianCalendar c1 = new GregorianCalendar();
                GregorianCalendar c2 = new GregorianCalendar();
                c1.setTime(today);
                c2.setTime(keg.getDateSold());
                int d1 = c1.get(Calendar.DAY_OF_YEAR);
                int d2 = c2.get(Calendar.DAY_OF_YEAR);
                int y1 = today.getYear();
                int y2 = keg.getDateSold().getYear();
                if (y1 == y2) {
                    days = d1 - d2;
                } else {
                    days = (365 - d2) + d1;
                    if ((y1 - y2) > 1) {
                        days = days + ((y1 - y2 - 1) * 365);
                    }
                }
            }
            boolean add = true;

            if (keg.getKegLost()) {
                add = false;
            }

            if (add) {
                if (keg.getKegCust() != null && keg.getKegBeer() != null) {
                    if ((beerID == 0) || (keg.getKegBeer().getbId() == beerID)) {
                        if ((custID == 0) || (keg.getKegCust().getCId() == custID)) {
                            if ((pkgID == 0) || (keg.getKegPackageID().getPackageTypeID() == pkgID)) {
                                if (keg.getDateSold() != null) {
                                    kArray.add(new KegReport(keg, custName, beerType, pkgType, days));
                                }
                            }
                        }
                    }
                }
            }
        }

        return kArray;
    }

    /*************************************************************************
     * Database access files.
     *************************************************************************/
    private List<ScanTblKeg> getAllKegs(final EntityManager en) {
        TypedQuery<ScanTblKeg> query = en.createQuery(
                "SELECT s FROM ScanTblKeg s", ScanTblKeg.class);
        return query.getResultList();
    }

    protected EntityManager getEntityManager() {
        return em;
    }
}
